package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.FullScreenImage;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.ReplyItem;
import chaw.android.util.ServerURL;
import chaw.android.util.TimeCheck;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "ParserError", "UseValueOf" })
public class BoardViewActivity extends ListActivity{
	private ArrayList<ReplyItem> list;
	private ReplyAdapter nadapter;
	private TextView title, nick_name, content, favorite_num, reply_num;
	private ImageButton write, favorite, reply;
	private ImageView back;
	private ImageView icon1, icon2, icon3, icon4, icon5;
	private ImageView img1, img2, img3, img4;
	private TextView station;
	private String now_icon = "1", favorite_check = "0";
	private String stationId, boardId, station_name;
	private String image1, image2, image3, image4;
	private Bitmap image_main = null, image_1 = null, image_2 = null, image_3 = null;
	private boolean addHeader = true;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.board_view);
	    list = new ArrayList<ReplyItem>();
	    back = (ImageView)findViewById(R.id.backBtn);
	    write = (ImageButton)findViewById(R.id.add_board);
	    favorite = (ImageButton)findViewById(R.id.favorite);
	    reply = (ImageButton)findViewById(R.id.reply);
	    favorite_num = (TextView)findViewById(R.id.favorite_num);
	    reply_num = (TextView)findViewById(R.id.reply_num);
		
	    setClickListener();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Intent intent = getIntent();
        boardId = intent.getExtras().get("board_id").toString();
        stationId = intent.getExtras().get("station_id").toString();
        station_name = intent.getExtras().get("station_name").toString();
        station = (TextView)findViewById(R.id.stationName);
		station.setText(station_name + "역");
		setListView();
	}
	
	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.downloadRepliesFromBoard, "board_id", boardId, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}

	private class BoardAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});
		}
	}
	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = urls[0];
			JSONObject data;
			try {
				data= new JSONObject(urls[0]);
				final JSONObject boarddata = (JSONObject) data.get("board");
				image1 = boarddata.get("image_url_1").toString();
				image2 = boarddata.get("image_url_2").toString();
				image3 = boarddata.get("image_url_3").toString();
				image4 = boarddata.get("image_url_4").toString();
				if(boarddata.get("image_main") != null && !boarddata.get("image_main").toString().equals("")){
					if(boarddata.get("image_main").toString().equals("0")){
						image_main = null;
					}
					else if(boarddata.get("image_main").toString().equals("1")){
						image_main = LoadBitMap.fromURL(image1);
						bitmapByMain(1, image1, image2, image3, image4);
					}
					else if(boarddata.get("image_main").toString().equals("2")){
						image_main = LoadBitMap.fromURL(image2);
						bitmapByMain(2, image1, image2, image3, image4);
					}
					else if(boarddata.get("image_main").toString().equals("3")){
						image_main = LoadBitMap.fromURL(image3);
						bitmapByMain(3, image1, image2, image3, image4);
					}
					else if(boarddata.get("image_main").toString().equals("4")){
						image_main = LoadBitMap.fromURL(image4);
						bitmapByMain(4, image1, image2, image3, image4);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			JSONObject data;
			try {
				data= new JSONObject(result);
				final JSONObject boarddata = (JSONObject) data.get("board");
				if(!boarddata.get("title").toString().equals("") && !boarddata.get("title").toString().equals("null") ){
					title.setText(boarddata.get("title").toString());
				}
				if(!boarddata.get("content").toString().equals("") && !boarddata.get("content").toString().equals("null")){
					content.setText(boarddata.get("content").toString());
				}
				if(!boarddata.get("nick_name").toString().equals("") && !boarddata.get("nick_name").toString().equals("null")){
					nick_name.setText(boarddata.get("nick_name").toString());
				}
				if(!boarddata.get("date").toString().equals("") && !boarddata.get("date").toString().equals("null")){
					((TextView)findViewById(R.id.date)).setText(TimeCheck.checkTime(boarddata.get("date").toString()));
				}
				nick_name.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
//		            	ActivityGroup parentActivity = (ActivityGroup) getParent();
						Intent intent = new Intent(getBaseContext(), TrainTravelActivity.class);
						try {
							intent.putExtra("user_id", boarddata.get("user_id").toString());
							intent.setFlags(FavoriteActivity.PROFILE_VIEW);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						startActivity(intent);
//		    			((FavoriteActivity) parentActivity).startChildActivity("Profile", intent);
					}
				});
				JSONObject theme = (JSONObject) boarddata.get("theme");
				themeIcon(theme);
				
				String favoritedata = data.get("favorite").toString();
				String replydata = data.get("reply").toString();
				String checkdata = data.get("check").toString();
				favorite_num.setText(favoritedata);
				reply_num.setText(replydata);
				favorite_check = checkdata;
				img1 = (ImageView)findViewById(R.id.image1);
				img2 = (ImageView)findViewById(R.id.image2);
				img3 = (ImageView)findViewById(R.id.image3);
				img4 = (ImageView)findViewById(R.id.image4);
				if(image_main != null)
					img1.setImageBitmap(image_main);
				if(image_1 != null)
					img2.setImageBitmap(image_1);
				if(image_2 != null)
					img3.setImageBitmap(image_2);
				if(image_3 != null)
					img4.setImageBitmap(image_3);
				img1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(image_main != null){
							Intent fullScreenImage = new Intent(getBaseContext(), FullScreenImage.class);
							fullScreenImage.putExtra("type", "url");
							fullScreenImage.putExtra("image", image1);
							startActivity(fullScreenImage);
						}
					}
				});
				img2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(image_1 != null){
							Intent fullScreenImage = new Intent(getBaseContext(), FullScreenImage.class);
							fullScreenImage.putExtra("type", "url");
							fullScreenImage.putExtra("image", image2);
							startActivity(fullScreenImage);
						}
					}
				});
				img3.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(image_2 != null){
							Intent fullScreenImage = new Intent(getBaseContext(), FullScreenImage.class);
							fullScreenImage.putExtra("type", "url");
							fullScreenImage.putExtra("image", image3);
							startActivity(fullScreenImage);
						}
					}
				});
				img4.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(image_3 != null){
							Intent fullScreenImage = new Intent(getBaseContext(), FullScreenImage.class);
							fullScreenImage.putExtra("type", "url");
							fullScreenImage.putExtra("image", image4);
							startActivity(fullScreenImage);
						}
					}
				});
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void bitmapByMain(int main_img, String image1, String image2, String image3, String image4){
		switch(main_img){
		case 1:
			if(!image2.equals(""))
				image_1 = LoadBitMap.fromURL(image2);
			if(!image3.equals(""))
				image_2 = LoadBitMap.fromURL(image3);
			if(!image4.equals(""))
				image_3 = LoadBitMap.fromURL(image4);
			break;
		case 2:
			if(!image1.equals(""))
				image_1 = LoadBitMap.fromURL(image1);
			if(!image2.equals(""))
				image_2 = LoadBitMap.fromURL(image3);
			if(!image3.equals(""))
				image_3 = LoadBitMap.fromURL(image4);
			break;
		case 3:
			if(!image1.equals(""))
				image_1 = LoadBitMap.fromURL(image1);
			if(!image2.equals(""))
				image_2 = LoadBitMap.fromURL(image2);
			if(!image4.equals(""))
				image_3 = LoadBitMap.fromURL(image4);
			break;
		case 4:
			if(!image1.equals(""))
				image_1 = LoadBitMap.fromURL(image1);
			if(!image2.equals(""))
				image_2 = LoadBitMap.fromURL(image2);
			if(!image3.equals(""))
				image_3 = LoadBitMap.fromURL(image3);
			break;
		}
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			list.clear();
			JSONObject ndata;
			try{
				ndata = new JSONObject(result);
				JSONArray json_arr = new JSONArray(ndata.getString("replies"));
				for(int i = 0 ; i < json_arr.length(); i++){
					String nick_name = "";
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					if(!json_obj.get("nick_name").toString().equals("") && json_obj.get("nick_name") != null){
						nick_name = json_obj.get("nick_name").toString();
					}
					ReplyItem input = new ReplyItem(json_obj.get("user_id").toString(), nick_name, json_obj.get("content").toString(), json_obj.get("date").toString());
					list.add(input);
				}
				nadapter = new ReplyAdapter(getBaseContext(), R.layout.board_view_row, R.id.board_title, list);
			    ListView lv = getListView();
			    View header = getLayoutInflater().inflate(R.layout.board_view_header, null, false);
		        title = (TextView)header.findViewById(R.id.title);
		        nick_name = (TextView)header.findViewById(R.id.userNickname);
		        content = (TextView)header.findViewById(R.id.content);
		        icon1 = (ImageView)header.findViewById(R.id.theme1);
		        icon2 = (ImageView)header.findViewById(R.id.theme2);
		        icon3 = (ImageView)header.findViewById(R.id.theme3);
		        icon4 = (ImageView)header.findViewById(R.id.theme4);
		        icon5 = (ImageView)header.findViewById(R.id.theme5);
				BoardAsynkTask task = new BoardAsynkTask();
				String[] params = new String[]{ServerURL.board, "board_id", boardId, "favorite_id", Preferences.getValue(getBaseContext(), "favorite_id") };
				task.execute(params);
		        if(addHeader){
		        	lv.addHeaderView(header);
		        	addHeader = false;
		        }
			    lv.setAdapter(nadapter);
			} catch(JSONException e){
				e.printStackTrace();
			}

		}
	}

	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result.equals("success")){
				Toast.makeText(getBaseContext(), "책갈피에 추가되었습니다..", Toast.LENGTH_SHORT).show();
				favorite_check = "1";
				int change = new Integer(favorite_num.getText().toString());
				favorite_num.setText(""+(change+1));
			}
			else{
				Toast.makeText(getBaseContext(), "책갈피에 추가에 실패하였습니다.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void setClickListener(){
		back.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		write.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(), BoardWriteActivity.class);
				intent.putExtra("station_id", stationId);
				intent.putExtra("station_name", station_name);
				startActivity(intent);
				}
		});
		favorite.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(favorite_check.equals("0")){
					UploadAsynkTask task = new UploadAsynkTask();
					String[] params = new String[]{ServerURL.addFavoriteBoard, "user_id", Preferences.getValue(getBaseContext(), "user_id"), "board_id", boardId};
					task.execute(params);
				}
				else{
					Toast.makeText(getBaseContext(), "이미 책갈피에 추가되어 있습니다.", Toast.LENGTH_SHORT).show();
				}
			}
		});
		reply.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(), ReplyWriteActivity.class);
				intent.putExtra("board_id", boardId);
				intent.putExtra("station_name", station_name);
				intent.putExtra("station_id", stationId);
				startActivity(intent);
				}
		});
	}

	private class ReplyAdapter extends ArrayAdapter<ReplyItem>{
		private ArrayList<ReplyItem> items;
		private int rsrc;
		
		public ReplyAdapter(Context ctx, int rsrcId, int txtId, ArrayList<ReplyItem> data){
			super(ctx, rsrcId, txtId, data);
			this.items = data;
			this.rsrc = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			}
			final ReplyItem e = items.get(position);
			if(e != null){
				TextView nickName = (TextView) v.findViewById(R.id.reply_nickName);
				nickName.setText(e.getName());
				((TextView)v.findViewById(R.id.reply_content)).setText(e.getContent());
				((TextView)v.findViewById(R.id.reply_date)).setText(TimeCheck.checkTime(e.getDate()));
				nickName.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
//						finish();
//		            	ActivityGroup parentActivity = (ActivityGroup) getParent();
//						Intent intent = new Intent(getBaseContext(), EachProfileActivity.class);
//						intent.putExtra("user_id", e.getId());
//		    			((FavoriteActivity) parentActivity).startChildActivity("Profile", intent);

						Intent intent = new Intent(getBaseContext(), TrainTravelActivity.class);
						try {
							intent.putExtra("user_id", e.getId());
							intent.setFlags(FavoriteActivity.PROFILE_VIEW);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						startActivity(intent);
					}
				});
			}
			return v;
		}
	}
	
	public void themeIcon(JSONObject themelist){
		try {
			if(((String)themelist.get("meet")).equals("1")){
				setImage(now_icon, R.drawable.icon_theme_meet);
				nextIcon();
			}
			if(((String)themelist.get("lodge")).equals("1")){
				setImage(now_icon, R.drawable.icon_theme_lodge);
				nextIcon();
			}
			if(((String)themelist.get("restaurant")).equals("1")){
				setImage(now_icon, R.drawable.icon_theme_food);
				nextIcon();
			}
			if(((String)themelist.get("place")).equals("1")){
				setImage(now_icon, R.drawable.icon_theme_tour);
				nextIcon();
			}
			if(((String)themelist.get("etc")).equals("1")){
				setImage(now_icon, R.drawable.icon_theme_etc);
				nextIcon();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void setImage(String setter, int resId){
		if(setter.equals("1")){
			icon1.setImageResource(resId);
		}
		else if(setter.equals("2")){
			icon2.setImageResource(resId);
		}
		else if(setter.equals("3")){
			icon3.setImageResource(resId);
		}
		else if(setter.equals("4")){
			icon4.setImageResource(resId);
		}
		else if(setter.equals("5")){
			icon5.setImageResource(resId);
		}
	}
	public void nextIcon(){
		if(now_icon.equals("1")){
			now_icon = "2";
		}
		else if(now_icon.equals("2")){
			now_icon = "3";
		}
		else if(now_icon.equals("3")){
			now_icon = "4";
		}
		else if(now_icon.equals("4")){
			now_icon = "5";
		}
	}
}
